package pattern;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 东莞呵呵
 * Date:2022-09-18
 * Time:10:39
 */

//单例类

// 饿汉模式  线程安全
class Singleton{
    private static Singleton Instance = new Singleton();

    //为了防止类外被实例化
    private Singleton(){

    }

    //类外使用该实例
    public static Singleton getInstance() {
        return Instance;
    }
}

//懒汉模式  线程不安全
class Singleton2{
    private static Singleton2 instance=null;

    public static Singleton2 getInstance() {
        if(instance==null){
            instance=new Singleton2();
        }
        return instance;
    }
}

//懒汉模式  线程安全
class Singleton3{
    private static Singleton3 instance=null;

    public static Singleton3 getInstance() {
        //判定是否要加锁
        if(instance==null){
            synchronized (Singleton3.class){
                //判断是否要创建实例
                if(instance==null){
                    instance=new Singleton3();
                }
            }
        }
        return instance;
    }
}
public class Demo1 {
}
